import Axios from 'axios'
import App from '../main'
import { session } from 'util/storage'

// const util = {
//   jsonToParams(json) {
//     let params = ''
//     for (const key in json) {
//       params += `&${key}=${encodeURIComponent(json[key])}`
//     }
//     return params.substring(1)
//   }
// }

// 建立请求
const request = (method, url, data, options) => {
  data.parent_code = 'meizhuang'
  App.$spin.show()
  // 如果是GET请求，则处理参数
  options = method === 'get' ? { params: options } : options
  let config = Object.assign({}, {
    // 默认配置
    method, url, data,
    timeout: 8000
  }, options)
  // 如果是POST请求，添加headers
  if (method === 'post') {
    config.headers = Object.assign({ 'Content-Type': 'application/json; charset=UTF-8' }, config.headers)
  }
  // 发起请求
  return Axios(url, config).then(result => {
    App.$spin.hide()
    const code = result.data.code
    if (/userExistInfo/.test(result.config.url)) {
      return result.data
    }
    if (code == 200 || code == 100000 || !code) {
      return result.data.data
    } else if (code == '1005' || code == '1006' || code == '1007' || code == '1008' || code == '1009' || code == '1010') { // token错误的情况下
      App.$toast('用户登录信息失效，请重新登录', () => {
        session.remove('userInfo')
        App.$router.push(`/login?redirect=${encodeURIComponent(App.$route.fullPath)}`)
      })
    } else if (code == '1004') {
      App.$toast(result.data.msg, () => {
        App.$router.push('/register')
      })
    } else if (code == '2000') {
      App.$toast('已收藏')
    } else {
      App.$toast(result.data.msg)
    }
  }).catch(err => {
    App.$toast('请求超时，请稍后在试')
    App.$spin.hide()
  })
}
// 导出
export default {
  get(url, config) {
    return request('get', url, null, config)
  },
  post(url, data, config) {
    return request('post', url, data, config)
  }
}